package com.diablo.sitemanager.controller;

import com.diablo.sitemanager.dao.ArticleMapper;
import com.diablo.sitemanager.entity.ArticleVo;
import com.diablo.sitemanager.service.ArticleService;
import com.diablo.sitemanager.util.FileUtil;
import com.diablo.sitemanager.util.QiniuUtil;
import com.google.gson.Gson;
import com.sun.deploy.net.HttpResponse;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 默认主页跳转
 * Created by diablo13064 on 2018/5/22.
 */
@Controller
public class MainController {
    private static String dir = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images/";
    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    QiniuUtil qiniuUtil;

    @Autowired
    ArticleService articleService;

    @RequestMapping("/")
    public String mainPage() {
        return "redirect:/admin/home";
    }
    //测试
    @RequestMapping("/test")
    @ResponseBody
    public Object testPage() throws IOException {

        //List<String> list = articleService.getImageList(dir);
        return articleMapper.selectAllAricle();
        //return "admin/test";
    }

    //上传图片文件
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<>();
        if (file != null && file.getOriginalFilename().indexOf(".") > -1) {
            map.put("errno", 0);
            String fileName = FileUtil.makeFileName(file);
            qiniuUtil.upload(file.getBytes(), fileName);
            map.put("data", new String[]{qiniuUtil.getPublicDownLink(fileName)});
        }
        //articleService.upload();
        String result = new Gson().toJson(map);
        return result;
    }
    private String getJarFileDir() {
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        return jarFile.getParentFile().getAbsolutePath();
    }
}
